package com.sias.springboot;

import org.springframework.boot.DefaultBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.support.SpringFactoriesLoader;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author 吴文杰
 * @version 1.0
 * @since 2023/6/22 15:13
 */
public class A39_1 {
  public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    SpringApplication app = new SpringApplication();
    app.addListeners(event -> System.out.println(event.getClass()));
    List<String> names = SpringFactoriesLoader.loadFactoryNames(SpringApplicationRunListener.class, A39_1.class.getClassLoader());
    for (String name : names) {
      System.out.println(name);
      Class<?> aClass = Class.forName(name);
      Constructor<?> constructor = aClass.getConstructor(SpringApplication.class, String[].class);
      SpringApplicationRunListener publisher = (SpringApplicationRunListener) constructor.newInstance(app, args);

      // 发布事件
      DefaultBootstrapContext bootContext = new DefaultBootstrapContext();
      publisher.starting(bootContext); // springboot 启动
      publisher.environmentPrepared(bootContext,new StandardEnvironment()); // 环境信息准备完毕
      GenericApplicationContext applicationContext = new GenericApplicationContext();
      publisher.contextPrepared(applicationContext);// 在spring容器创建，并调用初始化器之后，发送此事件
      publisher.contextLoaded(applicationContext);//所有bean definition加载完毕
      applicationContext.refresh();
      publisher.started(applicationContext); //spring 容器启动初始化完成（refresh方法调用完毕）
      publisher.running(applicationContext);//springboot启动完毕
      publisher.failed(applicationContext,new Exception("出错了"));//springboot 启动出错
    }

  }
}
